package com.huluspace.learnhub.controller;

import com.huluspace.learnhub.dto.*;
import com.huluspace.learnhub.model.User;
import com.huluspace.learnhub.security.JwtUtil;
import com.huluspace.learnhub.service.JwtAuthService;
import com.huluspace.learnhub.service.UserService;
import jakarta.servlet.http.HttpServletRequest;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.time.LocalDate;
import java.time.format.DateTimeParseException;
import java.util.Optional;

@Slf4j
@RestController
@RequestMapping("/api/user")
public class UserController {
  // 注入
  private final UserService userService;
  private final JwtUtil jwtUtil;
  private final JwtAuthService jwtAuthService;
  public UserController(UserService userService, JwtUtil jwtUtil, JwtAuthService jwtAuthService) {
    this.userService = userService;
    this.jwtUtil = jwtUtil;
    this.jwtAuthService = jwtAuthService;
  }

  // 用户列表
  // 获取用户分页列表
  @GetMapping("/list")
  public ApiResponse<PageResult<UserDTO>> list(
      @RequestParam(name = "page", defaultValue = "1") int page,
      @RequestParam(name = "pageSize", defaultValue = "10") int pageSize,
      @RequestParam(name = "username", required = false) String username
  ) {
    System.out.println("==> 接收到请求: page=" + page + ", pageSize=" + pageSize);
    PageResult<UserDTO> result = userService.getUsers(page, pageSize, username);
    return ApiResponse.success(result);
  }

  @PutMapping("/password")
  public ApiResponse<String> changePassword(@RequestBody PasswordChangeRequest request, HttpServletRequest httpRequest) {
    try {
      String username = jwtUtil.extractUserName(jwtUtil.extractToken(httpRequest));
      userService.changePassword(username, request.getOldPassword(), request.getNewPassword());
      return ApiResponse.success("密码修改成功");
    } catch (IllegalArgumentException e) {
      return ApiResponse.error(e.getMessage());
    }
  }

  // 用户信息
  @GetMapping("/me")
  public ApiResponse<UserDTO> getUserInfo(HttpServletRequest request) {
    // 从请求头提取token
    String token = jwtUtil.extractToken(request);
    // 解析用户名
    String username = jwtUtil.extractUserName(token);
    Optional<User> userOpt = userService.findByUsername(username);
    if (userOpt.isEmpty()) {
      return ApiResponse.error("用户不存在");
    }
    User user = userOpt.get();
    UserDTO dto = new UserDTO();
    dto.setUsername(user.getUsername());
    dto.setEmail(user.getEmail());
    dto.setPhone(user.getPhone());
    dto.setAddress(user.getAddress());
    dto.setRealName(user.getRealName());
    dto.setAvatar(user.getAvatar());
    dto.setGender(user.getGender() != null ? user.getGender().name() : null); // 枚举转字符串
    dto.setBirthDate(user.getBirthDate()); // LocalDate 直接赋值
    return ApiResponse.success(dto);
  }

  // 去激活某个用户（如禁止登录）
  @PostMapping("/deactivate")
  public ResponseEntity<String> deactivateUser(@RequestParam String username) {
    userService.deactivateUser(username);
    return ResponseEntity.ok("用户已去激活");
  }

  // 更新用户信息
  @PutMapping("/update")
  public ApiResponse<String> updateUser(@RequestBody UserUpdateDTO updateDTO,
                                      HttpServletRequest request) {
    // 从请求头提取token
    String token = jwtUtil.extractToken(request);
    // 解析用户名
    String username = jwtUtil.extractUserName(token);

    // 查找用户实体
    Optional<User> userOpt = userService.findByUsername(username);
    if (userOpt.isEmpty()) {
      return ApiResponse.error("用户不存在");
    }

    User user = userOpt.get();

    // 更新字段
    if (updateDTO.getRealName() != null) {
      user.setRealName(updateDTO.getRealName());
    }
    if (updateDTO.getGender() != null) {
      user.setGender(updateDTO.getGender());
    }
    if (updateDTO.getBirthDate() != null) {
      try {
        user.setBirthDate(LocalDate.parse(updateDTO.getBirthDate()));
      } catch (DateTimeParseException e) {
        // 解析失败，记录日志或忽略处理
        log.warn("无效的日期格式：{}", updateDTO.getBirthDate());
      }
    }
    if (updateDTO.getPhone() != null) {
      user.setPhone(updateDTO.getPhone());
    }
    if (updateDTO.getEmail() != null) {
      user.setEmail(updateDTO.getEmail());
    }
    if (updateDTO.getAddress() != null) {
      user.setAddress(updateDTO.getAddress());
    }

    // 保存更新
    userService.updateUser(user);

    return ApiResponse.success("信息更新成功");
  }


  @GetMapping("/roles")
  public ApiResponse<UserRolesDTO> getUserRoles(HttpServletRequest request) {
    User user = jwtAuthService.resolveUserFromRequest(request);
    return ApiResponse.success(new UserRolesDTO(user.getUsername(), user.roleNames()));
  }
}
